﻿#include "client_slot.h"
#include "user_define.h"
#include "log.h"

CClientSlot::CClientSlot(uint32_t maxTaskCount)
	: m_queue_socket(maxTaskCount)
	, m_queue_server_socket(maxTaskCount)
	, m_running(false)
{
	_safe_guard_begin;
	_safe_guard_end;
}

//-------------------------------------------------------------------------------
CClientSlot::~CClientSlot(void)
{
	Stop();
}

//-------------------------------------------------------------------------------
void CClientSlot::Start(void)
{
	_safe_guard_begin;
	
	m_running = true;

	m_thread = std::make_shared<std::thread>(&CClientSlot::RunThread, this);


	_safe_guard_end;
}

//-------------------------------------------------------------------------------
void CClientSlot::Stop(void)
{
	_safe_guard_begin;

	//	多线程下只调用一次
	std::call_once(m_flag, [this] {stopThread(); });

	_safe_guard_end;
}

//-------------------------------------------------------------------------------
void CClientSlot::stopThread(void)
{
	_safe_guard_begin;

	LOG_INFO("default"," stopThread");

	m_queue_socket.Stop();		//	同步队列中的线程停止
	m_queue_server_socket.Stop();	//	同步队列中的线程停止
	m_running = false;			//	内部线程跳出循环并退出

	m_thread->join();

	LOG_INFO("default","Stoped: Queue Count : socket : %d; internal : %d",
		(uint32_t)(m_queue_socket.Size()), (uint32_t)(m_queue_server_socket.Size()));

	_safe_guard_end;
}

//-------------------------------------------------------------------------------
void CClientSlot::AddClientMsgPtr(CClientSocketMsg& val)
{
	_safe_guard_begin;

	//LOG_DEBUG("default","Recv Client msgId: 0x%04X(%u) len %d", val->m_protocol_number, val->m_protocol_number, val->m_msg_size);
	
	if (m_queue_socket.IsFull())
	{
		LOG_ERROR("default","m_queue_socket.IsFull() : %d", (uint32_t)(m_queue_socket.Count()));
	}

	LOG_INFO("default","m_threadId=%s,m_queue_socket.Count() : %d", m_threadId.c_str(), (uint32_t)(m_queue_socket.Count()));
	// socket阻塞了，需要报警
	uint32_t count = (uint32_t)(m_queue_socket.Count());
	if (count > 5000)
	{
		LOG_WARN("default","error m_threadId=%s m_queue_socket.Count() : %u", m_threadId.c_str(), count);
	}

	m_queue_socket.Put(val);

	_safe_guard_end;
}

//-------------------------------------------------------------------------------
void CClientSlot::AddServerMsgPtr(CProxySocketMsg& val)
{
	_safe_guard_begin;
	
	m_queue_server_socket.Put(val);

	_safe_guard_end;
}
